import React, { useState, useEffect } from 'react'
// import { Link } from 'react-router-dom'
import Header from '../../components/Header/Header'// 头部组件
import { Tabs, Badge, Button, Radio, Empty, SwipeAction, Toast } from 'antd-mobile'
import './Shop.less'// less样式
import { reqCartDel, reqCartEdit, reqCartList } from '../../request/api'
// 导航栏组件
import Tablist from '../../components/Tablist/Tablist'
import { imgPre } from '../../request/http'
import { filterPrice } from '../../filters/index'

let isRequest = true;
const Shop = () => {
  // 1.初始化状态
  const [arr, setArr] = useState(['全部', '降价', '常卖', '分类']);
  const [shops, setShops] = useState([]);
  const [isAllcheck, setIsAllCheck] = useState(false);

  // 请求列表数据
  const requestList = () => {
    let uid = JSON.parse(sessionStorage.getItem('userinfo')).uid;
    reqCartList({ uid }).then(res => {
      if (res.data.code === 200) {
        let arr1 = res.data.list[0].content ? res.data.list[0].content : [];
        let arr2 = res.data.list[1].content ? res.data.list[1].content : [];
        let newArr = [...arr1, ...arr2];
        newArr.forEach(item => {
          let obj = shops.find(i => i.id === item.id);
          item.ischeck = obj ? obj.ischeck : false;
        })
        // 赋值给shops
        setShops(newArr);
        // 修改全选
        setIsAllCheck(newArr.length > 0 ? newArr.every(item => item.ischeck) : false);
        isRequest=true;
      }
    })
  }
  // 2.一进页面发请求
  useEffect(() => {
    requestList();
  }, []);

  // 删除
  const del = (index, id) => {
    reqCartDel({ id }).then(res => {
      if (res.data.code === 200) {
        Toast.show({
          content: res.data.msg
        })
        // 删除成功再重新请求列表
        requestList();
      }
    })
  }

  // 单个选
  const changeOne = (e, index) => {
    shops[index].ischeck = e;
    // 修改shops
    setShops([...shops]);
    // 修改全选的状态
    setIsAllCheck(shops.every(item => item.ischeck))
  }

  // 全选
  const changeAll = (e) => {
    setIsAllCheck(e);
    shops.forEach(item => {
      item.ischeck = e;
    })
    setShops([...shops]);
  }
  // ++
  const add = (id) => {
    reqCartEdit({ id, type: 2 }).then(res => {
      requestList();
    })
  }
  // --
  const sub = (id,num) => {
    if(num<=1){
      Toast.show({
        content:'宝贝的数量不能再少了哦'
      })
      return;
    }
    if(isRequest){
      isRequest=false;
      reqCartEdit({ id, type: 1 }).then(res => {
        requestList();
      })
    }
  }
  // 总价
  let sum = 0;
  shops.forEach(item => {
    if (item.ischeck) {
      sum += item.price * item.num;
    }
  })
  return (
    <div className='shop'>
      <Header title="购物车" back></Header>
      <Tablist arr={arr}></Tablist>
      <div className='list'>
        {shops.length > 0 ?
          <>
            {shops.map((item, index) => {
              return <SwipeAction
                rightActions={[
                  {
                    key: 'delete',
                    text: '删除',
                    color: 'danger',
                  },
                ]}
                key={item.id}
                onAction={(index) => del(index, item.id)}
              >
                <div className='check' >
                  <Radio checked={item.ischeck} onChange={(e) => changeOne(e, index)}></Radio>
                  <div className='item' >

                    <div className='left'>
                      <img src={imgPre + item.img} alt="" />
                    </div>
                    <div className='right'>
                      <h3>{item.goodsname}</h3>
                      <div>
                        <span>{'￥' + filterPrice(item.price ? item.price : 0)}</span>
                        <button onClick={() => sub(item.id,item.num)}>-</button>
                        <i>{item.num}</i>
                        <button onClick={() => add(item.id)}>+</button>
                      </div>
                    </div>
                  </div>
                </div>
              </SwipeAction>
            })}
          </> : <Empty description='暂无数据' />
        }
      </div>
      <div className='all'>
        <Radio checked={isAllcheck} onChange={(e) => changeAll(e)}>全选</Radio>
        <span>合计：{filterPrice(sum)}</span>
        <button>结算</button>
      </div>
    </div>
  )
}

export default Shop;